/**
 * inforcreation.com co.Ltd
 * @author MichaelHuang
 * Nov 10, 2011
 */
package com.zchat.api.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.webkit.CacheManager;
import android.widget.FrameLayout;

import com.zchat.android.R;
import com.zchat.api.FileDirProvider;
import com.zchat.api.log.Logger;

/**
 * @author MichaelHuang Utility class
 */
public class Helpers {

	/**
	 * show dialog
	 * 
	 * @param context
	 * @param title
	 *            Dialog title
	 * @param message
	 *            Dialog message
	 * @return
	 */
	public static AlertDialog.Builder showDialog(Context context, int title,
			int message, int[] buttonTexts, OnClickListener[] listeners) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(context);
		dialog.setTitle(title);
		dialog.setMessage(message);
		if (buttonTexts.length == 1) {
			dialog.setNeutralButton(buttonTexts[0], listeners[0]);
		} else if (buttonTexts.length == 2) {
			dialog.setPositiveButton(buttonTexts[0], listeners[0]);
			dialog.setNegativeButton(buttonTexts[1], listeners[1]);
		} else if (buttonTexts.length == 3) {
			dialog.setPositiveButton(buttonTexts[0], listeners[0]);
			dialog.setNeutralButton(buttonTexts[1], listeners[1]);
			dialog.setNegativeButton(buttonTexts[2], listeners[2]);
		}
		dialog.show();
		return dialog;
	}

	/**
	 * show dialog
	 * 
	 * @param context
	 * @param title
	 *            Dialog title
	 * @param message
	 *            Dialog message
	 * @return
	 */
	public static AlertDialog.Builder showDialog(Context context, String title,
			String message, int[] buttonTexts, OnClickListener[] listeners) {
		AlertDialog.Builder dialog = new AlertDialog.Builder(context);
		dialog.setTitle(title);
		dialog.setMessage(message);
		if (buttonTexts.length == 1) {
			dialog.setNeutralButton(buttonTexts[0], listeners[0]);
		} else if (buttonTexts.length == 2) {
			dialog.setPositiveButton(buttonTexts[0], listeners[0]);
			dialog.setNegativeButton(buttonTexts[1], listeners[1]);
		} else if (buttonTexts.length == 3) {
			dialog.setPositiveButton(buttonTexts[0], listeners[0]);
			dialog.setNeutralButton(buttonTexts[1], listeners[1]);
			dialog.setNegativeButton(buttonTexts[2], listeners[2]);
		}
		dialog.show();
		return dialog;
	}

	/**
	 * show progress dialog
	 * 
	 * @param context
	 * @param title
	 *            Dialog title
	 * @param message
	 *            Dialog message
	 * @return
	 */
	public static ProgressDialog showProgressDialog(Context context, int title,
			int message) {
		ProgressDialog dialog = new ProgressDialog(context);
		dialog.setTitle(title);
		dialog.setMessage(context.getResources().getString(message));
		dialog.setIndeterminate(true);
		dialog.setCancelable(true);
		dialog.show();
		return dialog;
	}

	/**
	 * 获得空progressDialog
	 * 
	 * @param context
	 * @return
	 */
	public static ProgressDialog showProgressDialog(Context context) {
		ProgressDialog dialog = new ProgressDialog(context);
		dialog.setIndeterminate(true);
		dialog.setCancelable(true);
		dialog.show();
		return dialog;
	}

	/**
	 * 关闭progress dialog
	 * 
	 * @param progressDialog
	 */
	public static void closeProgressDialog(Dialog progressDialog) {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.cancel();
		}
	}
	
	/**
	 * 从assets中读取图片
	 * @param context
	 * @param fileName
	 * @return
	 */
	 public static  Drawable  getImageFromAssetFile(Context context,String fileName){   
		 Drawable image = null;   
		 try{   
			AssetManager am = context.getAssets();   
		    InputStream is = am.open(fileName);   
		    image = new BitmapDrawable(is); 
		    is.close();   
		 }catch(Exception e){   
		       e.printStackTrace();    
		 }   
		 return image;   
	 } 
	 
	/**
	 * Returns a comma-delimitted list of Strings as a Collection.
	 * 
	 * @return a Collection representing the String.
	 */
	public static Collection<String> stringToCollection(String string) {
		if (string == null || string.trim().length() == 0) {
			return Collections.emptyList();
		}
		Collection<String> collection = new ArrayList<String>();

		StringTokenizer tokens = new StringTokenizer(string, ",");
		while (tokens.hasMoreTokens()) {
			collection.add(tokens.nextToken().trim());
		}
		return collection;
	}

	/**
	 * combina the url. usr the param list repleace the [#] in the url.
	 * 
	 * @param str
	 * @param params
	 * @return
	 * @exception RuntimeException
	 *                May throw the runtime exception while the method was done.
	 * @author MichaelHuang
	 */
	public static String combinaStr(String str, List<String> params)
			throws RuntimeException {
		try {
			String[] strs = str.split("[#]");
			String newStr = "";
			for (int i = 0; i < strs.length; i++) {
				String itemUrl = strs[i];
				newStr += itemUrl;
				if (i >= 0 && i < params.size())
					newStr += params.get(i);
			}
			// Logger.debug("do: " + newStr);
//			System.out.println("测试地址newString：" + newStr);
			return newStr;
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	/**
	 * Format date to string.
	 * 
	 * @param date
	 * @return
	 */
	public static String dateToString(Date date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.format(date);
	}

	/**
	 * 返回 yyyy-MM-dd 格式 的当前的时间 * @return
	 */
	public static String getFixFormatDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		return format.format(date);
	}

	/**
	 * 返回 yyyy-MM-dd HH:mm:ss 格式 的当前的时间 * @return
	 */
	public static String getAccurateFixFormatDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		return format.format(date);
	}

	/**
	 * string parse to date
	 * 
	 * @param str
	 * @return
	 * @throws ParseException
	 */
	public static Date stringToDate(String str) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return format.parse(str);
	}

	public static String collectionToString(Collection<String> s) {
		String delimiter = ",";
		if (s.isEmpty())
			return "";
		Iterator<String> iter = s.iterator();
		StringBuffer buffer = new StringBuffer(iter.next());
		while (iter.hasNext()) {
			buffer.append(delimiter);
			buffer.append(iter.next());
		}
		return buffer.toString();
	}

	/**
	 * 从文件中读取字符串，主要用作读取收藏的内容
	 * 
	 * @param path
	 * @return
	 */
	public static String readFileGetStr(String path) {
		try {
			File file = new File(path);
			if (file == null || !file.exists() || file.isDirectory()) {
				return null;
			}
			InputStream inputStream = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int len = -1;
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			while ((len = inputStream.read(buffer)) > -1) {
				outputStream.write(buffer, 0, len);
			}
			return new String(outputStream.toByteArray());
		} catch (Exception e) {

			e.printStackTrace();
			return null;
		}

	}

	public static String readFile(InputStream in) throws IOException {
		StringBuffer contentBuf = new StringBuffer();
		InputStreamReader isr = new InputStreamReader(in);
		BufferedReader br = new BufferedReader(isr);

		String data = null;
		while ((data = br.readLine()) != null) {
			contentBuf.append(data + "\n");
		}
		return contentBuf.toString();
	}

	public static boolean writeFile(InputStream in, String path)
			throws Exception {
		if (in == null) {
			return false;
		}
		try {
			File dest = new File(path);
			createNewFile(dest);
			OutputStream out = new FileOutputStream(dest);
			byte[] buf = new byte[1024];
			int i = 0;
			while ((i = in.read(buf)) > 0) {
				out.write(buf, 0, i);
			}
			// out.flush();
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * write file to dest path
	 * 
	 * @param in
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static boolean writeImage(InputStream in, String path)
			throws Exception {
		if (in == null) {
			return false;
		}
		try {
			File dest = new File(path);
			createNewFile(dest);
			OutputStream out = new FileOutputStream(dest);
			byte[] buf = new byte[1024];
			int i = 0;
			while ((i = in.read(buf)) > 0) {
				out.write(buf, 0, i);
			}
			// out.flush();
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
			// 校验文件完整性，如未下载完全，则直接删除
			InputStream fis = new FileInputStream(dest);
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inTempStorage = new byte[2 * 1024];
			opts.inSampleSize = 8;
			SoftReference<Bitmap> bitmap = new SoftReference<Bitmap>(
					BitmapFactory.decodeStream(fis, null, opts));
			if (fis != null) {
				fis.close();
			}
			if (bitmap.get() == null) {
				// 图片文件不完整，进行删除
				dest.delete();
			} else {
				bitmap.get().recycle();
			}
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * create new file
	 * 
	 * @param f
	 * @throws Exception
	 */
	public static void createNewFile(File f) throws Exception {
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		if (!f.exists()) {
			f.createNewFile();
		}
	}

	private static final String ACTION_INSTALL_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";

	/*
	 * 是否可以有多个快捷方式的副本
	 */
	static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";

	/**
	 * install shortcut on desktop
	 * 
	 * @param context
	 */
	public static void installShortCut(final Context context) {
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, context
				.getResources().getString(R.string.app_name));
		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
		Intent intent2 = new Intent(Intent.ACTION_MAIN);
		intent2.addCategory(Intent.CATEGORY_LAUNCHER);

		intent2.setComponent(new ComponentName(context.getPackageName(),
				context.getPackageName() + ".app.entry.BootActivity"));

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(context,
						R.drawable.ic_launcher));
		context.sendBroadcast(shortcutIntent);
	}


	/**
	 * get file name from url
	 * 
	 * @param url
	 */
	public static String getFileNameFromUrl(String url) {
		if (url != null && !url.equals("")) {
			return url.substring(url.lastIndexOf("/") + 1);
		}
		return url;
	}


	/**
	 * string to int value
	 * 
	 * @param str
	 * @return
	 */
	public static int stringToInt(String str) {
		if (str == null || str.equals("")) {
			return -1;
		} else {
			int result = -1;
			try {
				result = Integer.parseInt(str);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return result;
		}
	}

	/**
	 * get current month
	 * 
	 * @return
	 */
	public static int getCurrentMouth() {
		Calendar c = Calendar.getInstance();
		return c.get(Calendar.MONTH) + 1;
	}

	public static ProgressDialog showProgress(Context context,
			CharSequence title, CharSequence message, boolean indeterminate,
			boolean cancelable) {
		ProgressDialog dialog = new ProgressDialog(context);
		dialog.setTitle(title);
		dialog.setMessage(message);
		dialog.setIndeterminate(indeterminate);
		dialog.setCancelable(cancelable);
		dialog.show();
		return dialog;
	}

	/**
	 * 得到md5加密后的字符串
	 * 
	 * @param plainText
	 * @return
	 */
	public static String MD5(String plainText) {
		String result = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			result = buf.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 递归删除目录
	 * 
	 * @param dir
	 */
	public static void deleteDir(File dir) {
		if (dir.exists() && dir.isDirectory()) {
			File[] childs = dir.listFiles();
			for (File f : childs) {
				if (f.exists() && f.isDirectory()) {
					deleteDir(f);
				} else if (f.exists()) {
					deleteFile(f);
				}
			}
			dir.delete();
		} else if (dir.exists()) {
			deleteFile(dir);
		}
	}

	/**
	 * 删除指定目录下的文件
	 * 
	 * @param dir
	 */
	public static void deleteFile(File dir) {
		if (dir.exists() && dir.isDirectory()) {
			File[] childs = dir.listFiles();
			for (File f : childs) {
				if (f.exists() && f.isDirectory()) {
					continue;
				} else if (f.exists() && f.isFile()) {
					f.delete();
				}
			}
			dir.delete();
		} else if (dir.exists() && dir.isFile()) {
			dir.delete();
		}
	}
	
	/**
	 * 删除Shared_Preference文件
	 */
	public static void deleteSharedPrfs(Context context, String shared_prfs_name) {
		SharedPreferences data = context.getSharedPreferences(shared_prfs_name,
				Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
		data.edit().clear().commit();
	}

	/**
	 * 控制AlertDialog点击不消失
	 * 
	 */
	public static void controlDialogShow(DialogInterface dialog) {
		try {
			Field field = dialog.getClass().getSuperclass().getDeclaredField(
					"mShowing");
			field.setAccessible(true);
			field.set(dialog, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return;

	}

	/**
	 * 控制AlertDialog点击消失
	 * 
	 */
	public static void controlDialogCancel(DialogInterface dialog) {
		try {
			Field field = dialog.getClass().getSuperclass().getDeclaredField(
					"mShowing");
			field.setAccessible(true);
			field.set(dialog, true);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	
	public static long getTimeMillions(int hour, int minute) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, hour);
		c.set(Calendar.MINUTE, minute);
		long time = c.getTimeInMillis();
		Logger.debug("time : " + time);
		return time;
	}
}
